package me.cxlr.qinlauncher2.view.drawer;

import android.annotation.SuppressLint;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.widget.AppCompatEditText;
import androidx.appcompat.widget.LinearLayoutCompat;
import androidx.appcompat.widget.PopupMenu;
import androidx.appcompat.widget.SearchView;
import androidx.fragment.app.Fragment;
import androidx.lifecycle.ViewModelProvider;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import java.util.List;
import java.util.Objects;

import me.cxlr.qinlauncher2.R;
import me.cxlr.qinlauncher2.adapter.drawer.DrawerAdapter;
import me.cxlr.qinlauncher2.constants.Constants;
import me.cxlr.qinlauncher2.constants.LauncherAction;
import me.cxlr.qinlauncher2.manager.ActionManager;
import me.cxlr.qinlauncher2.model.App;
import me.cxlr.qinlauncher2.model.AppAndFolder;
import me.cxlr.qinlauncher2.util.SharedPreferencesUtil;
import me.cxlr.qinlauncher2.util.ThemeUtil;
import me.cxlr.qinlauncher2.util.ToastUtil;
import me.cxlr.qinlauncher2.viewmodel.drawer.DrawerViewModel;

/**
 * 应用抽屉 Fragment
 *
 * @author 酷安用户:山轮纸
 */
public class DrawerFragment extends Fragment {

    private DrawerViewModel viewModel;
    private RecyclerView recyclerView;
    private DrawerAdapter adapter;
    private List<AppAndFolder> appAndFolderList;

    private LinearLayoutCompat llMenu;
    private SearchView searchView;

    int drawerStyle;
    int drawerSorting;
    int drawerSystemAppSorting;

    @Override
    public void onAttach(@NonNull Context context) {
        super.onAttach(context);

        // ViewModel
        viewModel = new ViewModelProvider(this).get(DrawerViewModel.class);
    }

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        // View
        View root = inflater.inflate(R.layout.fragment_drawer, container, false);
        recyclerView = root.findViewById(R.id.drawer_rv_app_list);

        searchView = root.findViewById(R.id.drawer_search);
        searchView.setVisibility(View.INVISIBLE);

        llMenu = root.findViewById(R.id.drawer_ll_menu);

        startAddAndRemoveReceiver();
        return root;
    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
    }

    @Override
    public void onStart() {
        super.onStart();
    }

    @Override
    public void onResume() {
        super.onResume();

        ThemeUtil.initTheme();

        drawerStyle = Integer.parseInt(SharedPreferencesUtil.getInstance().getString("app_drawer_style", "0"));
        drawerSorting = Integer.parseInt(SharedPreferencesUtil.getInstance().getString("app_drawer_sort", "0"));
        drawerSystemAppSorting = Integer.parseInt(SharedPreferencesUtil.getInstance().getString("app_drawer_system_sort", "0"));

        setLayoutManager(drawerStyle, recyclerView);
        searchView.setIconifiedByDefault(false);
        viewModel.getAppAndFolderList(drawerSorting,drawerSystemAppSorting).observe(getViewLifecycleOwner(), appAndFolderList -> {
            this.appAndFolderList = appAndFolderList;
            adapter = new DrawerAdapter(DrawerFragment.this, viewModel, this.appAndFolderList, drawerStyle);
            recyclerView.setAdapter(adapter);
            //监听RecyclerView滚动状态
            recyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
                @Override
                public void onScrollStateChanged(@NonNull RecyclerView recyclerView, int newState) {
                    super.onScrollStateChanged(recyclerView, newState);
                    if (recyclerView.getLayoutManager() != null) {
                        getPositionAndOffset();
                    }
                }
            });
        });

        llMenu.setOnClickListener(v -> createMenu(llMenu));
    }

    @Override
    public void onPause() {
        super.onPause();
    }

    @Override
    public void onStop() {
        super.onStop();
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();

        closeReceiver();
    }

    @Override
    public void onDetach() {
        super.onDetach();
    }

    /**
     * 设置列表布局
     *
     * @param appDrawerStyle 布局类型
     * @param recyclerView   RecyclerView
     */
    private void setLayoutManager(int appDrawerStyle, RecyclerView recyclerView) {
        switch (appDrawerStyle) {
            case Constants.APP_DRAWER_STYLE_GRID:
                recyclerView.setLayoutManager(new GridLayoutManager(getContext(), 3));
                break;
            case Constants.APP_DRAWER_STYLE_LINEAR:
                recyclerView.setLayoutManager(new LinearLayoutManager(getContext(), LinearLayoutManager.VERTICAL, false));
                break;
            default:
                break;
        }
    }

    /**
     * 右上角菜单
     */
    @SuppressLint("NonConstantResourceId")
    private void createMenu(View view) {
        PopupMenu popupMenu = new PopupMenu(requireContext(), view);
        popupMenu.getMenuInflater().inflate(R.menu.menu_app_drawer, popupMenu.getMenu());
        popupMenu.setOnMenuItemClickListener(item -> {
            switch (item.getItemId()) {
                case R.id.mad_launcher_settings:
                    ActionManager.getInstance().openAction(requireActivity(),requireContext(),LauncherAction.LAUNCHER_SETTINGS.getAction());
                    break;
                case R.id.mad_add_folder:
                    dialogCreateFolder();
                    break;
                default:
                    break;
            }
            return false;
        });
        popupMenu.show();
    }

    private AppCompatEditText etFolderName;

    /**
     * 创建文件夹
     */
    private void dialogCreateFolder() {
        View view = getLayoutInflater().inflate(R.layout.dialog_create_folder, null);

        etFolderName = view.findViewById(R.id.dcf_et_folder_name);

        AlertDialog dialogCreate = new AlertDialog.Builder(requireContext())
                .setPositiveButton("保存", (dialog, which) -> {
                    if ("".equals(Objects.requireNonNull(etFolderName.getText()).toString())) {
                        ToastUtil.show(requireContext(), "请输入文件夹名称", ToastUtil.LENGTH_LONG);
                    } else {
                        viewModel.saveFolder(etFolderName.getText().toString());
                        flush();
                        dialog.dismiss();
                    }
                })
                .setNegativeButton("取消", (dialog, which) -> dialog.dismiss())
                .setTitle("创建文件夹")
                .setView(view)
                .setCancelable(true)
                .create();
        dialogCreate.show();
    }

    private int lastOffset;
    private int lastPosition;

    /**
     * 列表刷新
     */
    public void flush() {
        viewModel.getAppAndFolderList(drawerSorting,drawerSystemAppSorting).observe(getViewLifecycleOwner(), appAndFolderList -> {
            this.appAndFolderList = appAndFolderList;
            adapter = new DrawerAdapter(DrawerFragment.this, viewModel, this.appAndFolderList, drawerStyle);
            recyclerView.setAdapter(adapter);
            scrollToPosition();
        });
    }

    /**
     * 记录RecyclerView当前位置
     */
    private void getPositionAndOffset() {
        RecyclerView.LayoutManager layoutManager = null;
        switch (drawerStyle) {
            case Constants.APP_DRAWER_STYLE_GRID:
                layoutManager = (GridLayoutManager) recyclerView.getLayoutManager();
                break;
            case Constants.APP_DRAWER_STYLE_LINEAR:
                layoutManager = (LinearLayoutManager) recyclerView.getLayoutManager();
                break;
            default:
                break;
        }
        //获取可视的第一个view
        assert layoutManager != null;
        View topView = layoutManager.getChildAt(0);
        if (topView != null) {
            //获取与该view的顶部的偏移量
            lastOffset = topView.getTop();
            //得到该View的数组位置
            lastPosition = layoutManager.getPosition(topView);
        }
    }

    /**
     * 滚动到之前的位置
     */
    private void scrollToPosition() {
        if (recyclerView.getLayoutManager() != null && lastPosition >= 0) {

            switch (drawerStyle) {
                case Constants.APP_DRAWER_STYLE_GRID:
                    ((GridLayoutManager) recyclerView.getLayoutManager()).scrollToPositionWithOffset(lastPosition, lastOffset);
                    break;
                case Constants.APP_DRAWER_STYLE_LINEAR:
                    ((LinearLayoutManager) recyclerView.getLayoutManager()).scrollToPositionWithOffset(lastPosition, lastOffset);
                    break;
                default:
                    break;
            }

        }
    }

    private AppDrawerReceiver receiver;

    /**
     * 监听app安装、卸载、变化和更新
     */
    private class AppDrawerReceiver extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {
            switch (Objects.requireNonNull(intent.getAction())) {
                // 安装 移除 替换 改变
                case Intent.ACTION_PACKAGE_ADDED:
                case Intent.ACTION_PACKAGE_REMOVED:
                case Intent.ACTION_PACKAGE_REPLACED:
                case Intent.ACTION_PACKAGE_CHANGED:
                    flush();
                    break;
                default:
                    break;
            }
        }
    }

    /**
     * 启动监听
     */
    private void startAddAndRemoveReceiver() {
        receiver = new AppDrawerReceiver();
        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction(Intent.ACTION_PACKAGE_ADDED);
        intentFilter.addAction(Intent.ACTION_PACKAGE_REMOVED);
        intentFilter.addAction(Intent.ACTION_PACKAGE_REPLACED);
        intentFilter.addAction(Intent.ACTION_PACKAGE_CHANGED);
        intentFilter.addDataScheme("package");
        requireContext().registerReceiver(receiver, intentFilter);
    }

    /**
     * 关闭监听
     */
    private void closeReceiver() {
        if (receiver != null) {
            requireContext().unregisterReceiver(receiver);
        }
    }
}
